package com.openness.spider.hbase;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;

/**
 * @author Rain
 * @version 2013-5-22 上午9:57:14
 */

public class HBaseUtil {

	public static List<Result> get(String tableName, List<Get> gets)
			throws IOException {
		if (tableName == null || tableName.length() == 0 || gets == null
				|| gets.size() == 0) {
			return null;
		}

		HTableInterface table = null;

		try {
			table = HBaseTablePool.get(tableName);

			Result[] results = table.get(gets);

			return Arrays.asList(results);
		} finally {
			if (table == null) {
				HBaseTablePool.put(table);
			}
		}
	}

	public static List<Result> get(String tableName, Scan scan, int max)
			throws IOException {
		if (tableName == null || tableName.length() == 0 || scan == null
				|| max <= 0) {
			return null;
		}

		HTableInterface table = null;

		ResultScanner rs = null;

		try {
			table = HBaseTablePool.get(tableName);

			rs = table.getScanner(scan);

			Result[] results = rs.next(max);

			return Arrays.asList(results);
		} finally {
			if (table != null) {
				HBaseTablePool.put(table);
			}
		}
	}

	public static boolean put(String tableName, List<Put> puts)
			throws IOException {
		if (tableName == null || tableName.length() == 0 || puts == null
				|| puts.size() == 0) {
			return false;
		}

		HTableInterface table = null;

		try {
			table = HBaseTablePool.get(tableName);

			table.put(puts);

			return true;
		} finally {
			if (table != null) {
				HBaseTablePool.put(table);
			}
		}
	}

	public static boolean delete(String tableName, List<Delete> deletes)
			throws IOException {
		if (tableName == null || tableName.length() == 0 || deletes == null
				|| deletes.size() == 0) {
			return false;
		}

		HTableInterface table = null;

		try {
			table = HBaseTablePool.get(tableName);

			table.delete(deletes);

			return true;
		} finally {
			if (table != null) {
				HBaseTablePool.put(table);
			}
		}
	}

}
